import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import store from "@/store/index";
import { getToken } from "@/utils/auth";
const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: "index",
    redirect: "/home",
    component: () => import("@/layout/index.vue"),
    children: [
      {
        path: "home",
        name: "home",
        component: () => import("@/views/Home.vue")
      },
      {
        path: "statistics",
        name: "statistics",
        component: () => import("@/views/Statistics.vue")
      },
      {
        path: "user",
        name: "user",
        component: () => import("@/views/User.vue")
      }
    ]
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/Login.vue")
  }
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});
const whiteList = ["/login", "/404", "/401"];
router.beforeEach(async (to, from, next) => {
  const hasToken = getToken();
  if (hasToken) {
    if (to.path === "/login") {
      next({ path: "/" });
    } else {
      const info = store.state.userInfo;
      if (info) {
        next();
      } else {
        try {
          await store.dispatch("getInfo");
          next({ ...to, replace: true });
        } catch (error) {
          //(token过期等情况)
          await store.dispatch("logout");
          next(`/login`);
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login`);
    }
  }
});

export default router;
